package top.yxqz.session.demo.web;

import top.yxqz.session.demo.school.Student;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/*
 * Session实现用户登录
 *   成功登录1分钟内，再次访问不用登录
 *   1分钟之后或者点击退出后需要重新登录(自动登录)
 * */
@WebServlet("/login")
public class sessionLoginServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //       创建相关对象
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();

        writer.println("<h1>Session自动登录</h1>");
//       创造数据
        String usernamedata = "zhangfei";
        String passwordData = "123456";


//        构建动态页面
        String uri = request.getRequestURI();
        writer.println("<form action=" + uri + ">\n" +
                "    用户名：<input type=\"text\" name=\"userName\"> <br>\n" +
                "    密 码：<input type=\"password\" name=\"password\"> <br>\n" +
                "    <input type=\"submit\" value=\"提交\">\n" +
                "</form>");

        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        String checkbox = request.getParameter("checkbox");
        System.out.println("前端输入的信息：" + userName);
        System.out.println("前端输入的信息：" + password);


        //设置账号root，密码123
        if (usernamedata.equals(userName) && passwordData.equals(password)) {
                //登录成功，将user对象保存到session域中
                Student loginUser = new Student();
                loginUser.setUserName(userName);
                loginUser.setPassword(password);
                request.getSession().setAttribute("user", loginUser);
                //创建cookie对象保存session的ID，同一个session才能获取同个用户
                Cookie c = new Cookie("JSESSIONID", request.getSession().getId());
                c.setMaxAge(60);
                c.setPath("/");
                response.addCookie(c);

            //登录成功跳转指定页面
            response.sendRedirect(getServletContext().getContextPath() + "/sessionIndexServlet");
        }
        else {
//        登录失败
            if (userName!=null){
                response.getWriter().write("账号或密码错误，请重新登录");
            }
        }
    }
}
